<template>
  <!-- 聊天对话 -->
  <div
    class="list"
    v-if="isLogin"
  >
    <div class="btn flexcc">
      <img
        v-show="listData.length > 3"
        src="@/assets/img/icon_xiala_sh.png"
        alt=""
        @click.stop="prev"
      />
    </div>

    <swiper
      class="mySwiper"
      direction="vertical"
      :modules="modules"
      :slides-per-view="3"
      :space-between="0"
      :mousewheel="true"
      @swiper="onSwiper"
      @slideChange="onSlideChange"
    >
      <swiper-slide
        v-for="(item, index) in listData"
        :key="item.id"
      >
        <div
          class="item flexcc"
          :title="item.customerName"
        >
          <img
            :src="item.customerAvatar || defaultAvatar"
            alt=""
            @click="openDialog(item)"
          />
          <div
            class="num flexcc"
            v-if="item.unreadNum > 0"
          >
            {{ item.unreadNum }}
          </div>
        </div>
      </swiper-slide>
    </swiper>

    <div class="btn flexcc">
      <img
        v-show="listData.length > 3"
        src="@/assets/img/icon_xiala_x.png"
        alt=""
        @click.stop="next"
      />
    </div>

    <!-- 对话框 -->
    <div class="mydialog">
      <el-dialog
        v-model="store.dialogVisible"
        title="Tips"
        width="520px"
        :show-close="false"
        :modal="false"
        draggable
        :close-on-click-modal="false"
        :lock-scroll="false"
      >
        <template #header="{ close, titleId, titleClass }">
          <div class="myheader flexsb">
            <h4
              :id="titleId"
              :class="[titleClass, 'mytitle']"
            >
              <!-- <div v-if="locale === 'zh-CN'">与{{ store.activePerson.customerName }}对话</div>
              <div v-if="locale === 'en'">Dialogue with {{ store.activePerson.customerName }}</div> -->
              <div @click="store.activePerson.customerId !== '0' && openUrl(`/member`, { id: store.activePerson.customerId })">{{ store.activePerson.customerName }}</div>
            </h4>
            <div class="dropdown">
              <el-dropdown
                trigger="click"
                placement="bottom-end"
                v-if="store.activePerson.customerId !== '0'"
              >
                <img
                  src="@/assets/img/icon_gengduo.png"
                  class="mr-1"
                  height="26"
                />
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="handleDelete">{{ t('dialogue.delete') }}</el-dropdown-item>
                    <el-dropdown-item @click="handleBlack">{{ t('dialogue.blockPerson') }}</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>

              <img
                src="@/assets/img/icon_guanbi2.png"
                @click="close"
                class="close"
                height="26"
              />
            </div>
          </div>
        </template>
        <div
          class="main"
          ref="mainEl"
        >
          <div
            v-if="isLoadmore"
            class="loadmore flexcc mb-2 mt-1"
            @click="loadmore"
          >
            {{ t('dialogue.viewHistory') }}
          </div>

          <div
            :class="['item', 'mb-2', { self: isSelf(sendingCustomerId) }]"
            v-for="{ id, customerAvatar, customerName, createTime, showTime, content, sendingCustomerId, state } in infoList"
            :key="id"
          >
            <div
              v-if="showTime"
              class="time flexcc"
            >
              {{ dateFilter(createTime) }}
            </div>
            <div class="user flexss">
              <img
                :src="customerAvatar || defaultAvatar"
                class="avatar mr-1"
                @click="store.activePerson.customerId !== '0' && !isSelf(sendingCustomerId) && openUrl(`/member`, { id: store.activePerson.customerId })"
              />
              <div>
                <!-- <div class="n">
                  <div class="name">{{ customerName }}</div>
                </div> -->
                <div :class="['content', `state-${state}`]">{{ content }}</div>
              </div>
            </div>
          </div>

          <!-- <div class="flexcc">No more at the moment...</div> -->
        </div>
        <template #footer>
          <div class="myfooter">
            <div class="input flexsc">
              <el-input
                ref="contentEl"
                v-model="content"
                type="textarea"
                :placeholder="t('dialogue.pleaseInput')"
                resize="none"
                :autosize="{ minRows: 4, maxRows: 4 }"
                @keydown.enter="handleSend"
              />
              <div class="emoji">
                <V3Emoji
                  ref="V3EmojiEl"
                  :disable-group="disableGroup"
                  :options-name="optionsName"
                  :custom-size="customSize"
                  @clickEmoji="clickEmoji"
                />
              </div>
            </div>
            <el-button
              type="primary"
              @click="handleSend"
            >
              {{ t('dialogue.send') }}
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, computed, onMounted, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { Swiper, SwiperSlide } from 'swiper/vue'
import { Mousewheel } from 'swiper'
import useDialogue from '@/stores/dialogue'
import useLogin from '@/stores/login'
import { sessionApi, getInfoListApi, getUnreadInfoListApi, getSendingUnreadInfoListApi, getListApi, deletePersonApi, blackPersonApi } from '@/service/common'
import { dateFormat, openUrl } from '@/utils'
import { useI18n } from 'vue-i18n'
import moment from 'moment'

const modules = [Mousewheel]

import V3Emoji from 'vue3-emoji'
import 'vue3-emoji/dist/style.css'

const { t, locale } = useI18n()
watch(locale, (n) => {
  init()
})

const router = useRouter()
const route = useRoute()

const store = useDialogue()
const { setDialogVisible, setActivePerson, reset } = store
watch([() => store.dialogVisible, () => store.activePerson.customerId], (n) => {
  resetData()

  if (n[0] && n[1]) {
    getInfoList()

    if (!timerInfo.value) {
      // 定时拉取未读
      timerInfo.value = setInterval(() => {
        getUnreadInfoList()
        getSendingUnreadInfoList()
      }, 1000 * 10)
    }
  }

  if (!n[0]) {
    clearInterval(timerInfo.value)
    timerInfo.value = null
    reset()
  }
})

// swiper
const myswiper = ref(null)
const onSwiper = (swiper) => {
  myswiper.value = swiper
}
const onSlideChange = () => {}
const prev = () => {
  myswiper.value.slideTo(myswiper.value.activeIndex - 3)
}
const next = () => {
  myswiper.value.slideTo(myswiper.value.activeIndex + 3)
}

// 联系人列表
const listData = ref([])

// 默认头像
const defaultAvatar = new URL('@/assets/img/icon_touxiang_01.png', import.meta.url)

// 获取列表
const getList = () => {
  getListApi().then(({ data }) => {
    const kf = data.find((item) => item.customerId === '0')

    if (kf) {
      data = data.filter((item) => item.customerId !== '0')
    }

    // 系统客服
    data.unshift({
      customerId: '0',
      customerName: t('dialogue.system'),
      customerAvatar: new URL('@/assets/img/kf.png', import.meta.url),
      unreadNum: kf ? kf.unreadNum : 0
    })

    listData.value = data
  })
}

// 获取会话数据
const page = ref({
  pageNum: 1, // 当前页码
  pageSize: 10 // 每页条数
})
const total = ref(0) // 总数
const infoList = ref([])
const getInfoList = (type = 'bottom') => {
  getInfoListApi(page.value, {
    receivedCustomerId: storeUseLogin.userInfo.id,
    sendingCustomerId: store.activePerson.customerId
  }).then(({ rows, total: tot }) => {
    rows.forEach((item) => {
      if (item.sendingCustomerId === 0) {
        item.customerName = t('dialogue.system')
        item.customerAvatar = new URL('@/assets/img/kf.png', import.meta.url)
      }
    })

    infoList.value = [...rows.reverse(), ...infoList.value]
    total.value = tot
    scrollTo(type)

    if (infoList.value.length >= total.value) {
      isLoadmore.value = false
    }
  })
}
// 加载更多
const isLoadmore = ref(true)
const loadmore = () => {
  page.value.pageNum++
  getInfoList('top')
}
// 重置
const resetData = () => {
  isLoadmore.value = true
  page.value.pageNum = 1
  infoList.value = []
  content.value = ''
}

// 每隔10分钟 显示时间
watch(
  infoList,
  (n) => {
    let t = null
    n.forEach((item, index) => {
      if (index === 0) {
        t = item.createTime
        item.showTime = true
      } else {
        if (item.createTime - t > 60 * 10) {
          t = item.createTime
          item.showTime = true
        }
      }
    })
  },
  { deep: true }
)

// 今年的不显示年 今天的只显示 时分
const dateFilter = (createTime) => {
  const isToday = moment.unix(parseInt(createTime)).format('YYYY-MM-DD') === moment().format('YYYY-MM-DD')
  const isThisYear = moment.unix(parseInt(createTime)).format('YYYY') === moment().format('YYYY')
  let str = ''
  if (isThisYear) {
    str = moment.unix(parseInt(createTime)).format(isToday ? 'HH:mm' : 'MM-DD HH:mm')
  } else {
    str = moment.unix(parseInt(createTime)).format('YYYY-MM-DD HH:mm')
  }
  return str
}

// 滚动到 顶部 底部
const mainEl = ref(null)
const scrollTo = (type) => {
  nextTick(() => {
    const obj = {
      top: 0,
      bottom: mainEl.value.scrollHeight
    }
    mainEl.value.scrollTo({ top: obj[type], behavior: 'smooth' })
  })
}

// 获取未读会话数据
const getUnreadInfoList = async () => {
  await getUnreadInfoListApi(null, {
    receivedCustomerId: storeUseLogin.userInfo.id,
    sendingCustomerId: store.activePerson.customerId
  }).then(({ data }) => {
    if (data.length) {
      infoList.value = [...infoList.value, ...data.reverse()]
      scrollTo('bottom')
    }
  })
}

// 查自己发的消息的已读状态
const getSendingUnreadInfoList = () => {
  getSendingUnreadInfoListApi(null, {
    receivedCustomerId: store.activePerson.customerId,
    sendingCustomerId: storeUseLogin.userInfo.id
  }).then(({ data }) => {
    if (data.length) {
      const ids = data.map((d) => d.id)
      infoList.value.forEach((item) => {
        item.state = ids.includes(item.id) ? '0' : '1'
      })
    } else {
      infoList.value.forEach((item) => {
        item.state = '1' // 状态(未读0 已读1)
      })
    }
  })
}

// 打开对话
const timerInfo = ref(null)
const openDialog = (item) => {
  if (store.activePerson.customerId === item.customerId) {
    return
  }
  infoList.value = []
  isLoadmore.value = true
  page.value.pageNum = 1
  item.unreadNum = 0

  setActivePerson(item)
  setDialogVisible(true)
}

const isSelf = (sendingCustomerId) => {
  return sendingCustomerId === storeUseLogin.userInfo.id
}

// 内容
const content = ref('')
const contentEl = ref(null)
// 表情
const V3EmojiEl = ref(null)
const optionsName = computed(() => {
  return {
    'Smileys & Emotion': t('dialogue.emoji.Smileys'),
    'Food & Drink': t('dialogue.emoji.Food'),
    'Animals & Nature': t('dialogue.emoji.Animals'),
    'Travel & Places': t('dialogue.emoji.Travel'),
    'People & Body': t('dialogue.emoji.People'),
    Objects: t('dialogue.emoji.Objects'),
    Symbols: t('dialogue.emoji.Symbols'),
    Flags: t('dialogue.emoji.Flags'),
    Activities: t('dialogue.emoji.Activities')
  }
})
const customSize = {
  // 'V3Emoji-width': '300px',
  // 'V3Emoji-height': '20rem',
  'V3Emoji-fontSize': '1.4rem'
  // 'V3Emoji-itemSize': '50px'
}
const disableGroup = [t('dialogue.emoji.Flags')]
// 点击表情
const clickEmoji = (val) => {
  // content.value = val
  if (!contentEl.value) return
  const dom = contentEl.value.textarea
  const index = dom.selectionStart
  let txt = dom.value
  content.value = txt.substring(0, index) + val + txt.substring(index, txt.length)
  nextTick(() => {
    dom.focus()
    dom.setSelectionRange(index + val.length, index + val.length)

    // 关闭表情框
    document.body.click()
  })
}
// 发送
const handleSend = () => {
  // console.log(store.activePerson.customerId)
  if (!content.value.trim()) return

  const params = {
    receivedCustomerId: store.activePerson.customerId,
    sendingCustomerId: storeUseLogin.userInfo.id,
    content: content.value
  }

  // console.log(params);
  sessionApi(params).then(async ({ data: { id, createTime, sendingCustomerId } }) => {
    await getUnreadInfoList()
    infoList.value.push({
      customerAvatar: storeUseLogin.userInfo.avatar,
      customerName: storeUseLogin.userInfo.userName,
      content: content.value,
      createTime,
      id,
      sendingCustomerId,
      state: '0'
    })
    content.value = ''
    scrollTo('bottom')
  })
}

// 删除
const handleDelete = () => {
  deletePersonApi(store.activePerson.customerId).then(({ msg }) => {
    setDialogVisible(false)
    getList()
  })
}

// 拉黑
const handleBlack = () => {
  blackPersonApi(store.activePerson.customerId).then(({ msg }) => {
    setDialogVisible(false)
    getList()
  })
}

// 登录后 获取列表
const timer = ref(null)
const storeUseLogin = useLogin()
watch(
  () => storeUseLogin.userInfo?.id,
  (n) => {
    if (n) {
      const fn = () => {
        getList()
        return fn
      }
      timer.value = setInterval(fn(), 1000 * 30)
    } else {
      clearInterval(timer.value)
      clearInterval(timerInfo.value)
      timer.value = null
      timerInfo.value = null
    }
  },
  {
    immediate: true
  }
)
const isLogin = computed(() => {
  return storeUseLogin.userInfo?.id
})

//
const init = () => {
  if (!isLogin.value) {
    return
  }
  getList()
}
</script>

<style scoped lang="scss">
.list {
  position: fixed;
  right: 10px;
  top: 225px;
  z-index: 999;
  width: 90px;
  height: 320px;
  background: rgba(255, 255, 255, 0.5);
  box-shadow: 0px 0px 28px 2px rgba(106, 105, 115, 0.1);
  border-radius: 4px;
  padding: 27px 0px;
  display: grid;
  grid-template-rows: 14px 237px 14px;

  .btn {
    cursor: pointer;
  }

  .mySwiper {
    overflow: hidden;

    .swiper-slide {
      .item {
        position: relative;
        height: 100%;
        width: 100%;

        img {
          width: 50px;
          height: 50px;
          cursor: pointer;
          border-radius: 50%;
        }

        .num {
          position: absolute;
          top: 15px;
          right: 0px;
          border-radius: 50%;
          min-width: 18px;
          height: 18px;
          background: var(--mainColor);
          color: #fff;
        }
      }
    }
  }

  .mydialog {
    pointer-events: none;

    .dropdown {
      cursor: pointer;
    }

    :deep(.el-dialog) {
      margin: 0;
      position: fixed;
      right: 110px;
      top: 10px;
      pointer-events: auto;

      .el-dialog__header {
        background: #29333d;

        .mytitle {
          color: #fff;

          img {
            cursor: pointer;
          }
        }
      }

      .el-dialog__body {
        background: #f5f5f5;
        padding-bottom: 0;
      }

      .main {
        height: 400px;
        overflow-y: auto;
        border-radius: 4px;

        &::-webkit-scrollbar {
          width: 5px;
          height: 5px;
        }

        &::-webkit-scrollbar-track {
          background: #f5f5f5;
        }

        &::-webkit-scrollbar-thumb {
          border-radius: 3px;
          background: #c1c1c1;
        }

        .loadmore {
          cursor: pointer;
        }

        .item {
          .time {
            color: #ccc;
            font-size: 12px;
            margin-bottom: 20px;
          }
          .user {
            .avatar {
              width: 45px;
              height: 45px;
              border-radius: 50%;
              background: #fff;
              cursor: pointer;
            }
            .n {
              margin-bottom: 10px;
            }
          }
          .content {
            background: #fff;
            border-radius: 6px;
            padding: 13px;
            max-width: 300px;
          }

          &.self {
            .user {
              flex-direction: row-reverse;
              .avatar {
                margin-right: 0;
                margin-left: 10px;
                cursor: default;
              }
              .n {
                text-align: right;
              }
            }

            .content {
              background: #10ecec;
              position: relative;

              &::after {
                content: '';
                display: block;
                position: absolute;
                left: -30px;
                top: 50%;
                width: 20px;
                height: 20px;
                transform: translateY(-50%);
              }

              &.state-0::after {
                background: url('@/assets/img/icon_weidu.png') no-repeat center;
              }

              &.state-1::after {
                background: url('@/assets/img/icon_yidu.png') no-repeat center;
              }
            }
          }
        }
      }

      .el-dialog__footer {
        background: #f5f5f5;
      }

      .myfooter {
        background: #fff;
        padding: 10px;
        border-radius: 4px;
        display: grid;
        grid-template-columns: auto 100px;
        gap: 10px;

        .input {
          position: relative;

          .emoji {
            position: absolute;
            bottom: 5px;
            right: 5px;
          }
        }

        .el-input__wrapper {
          box-shadow: none;
        }

        .el-button {
          width: 100px;
          height: 44px;
          text-transform: uppercase;
        }
      }
    }
  }
}
</style>
